import UIKit

// 老师1评分
func changeScores1(scores: inout [Int]) {
  for (idx, score) in scores.enumerated() {
    scores[idx] = Int(sqrt(Double(score * 10)))
  }
}

// 老师2评分
func changeScores2(scores: inout [Int]) {
  for (idx, score) in scores.enumerated() {
    scores[idx] = Int(sqrt(Double(score) / 15.0 * 100))
  }
}

var scores1 = [36, 61, 78, 89, 99]
changeScores1(scores: &scores1)

var scores2 = [88, 101, 124, 137, 150]
changeScores2(scores: &scores2)

// 优化: 每个老师传递自己的评分规则
func changeScore(scores: inout [Int], changeMethod: (Int) -> Int) {
  for (index, score) in scores.enumerated() {
    scores[index] = changeMethod(score)
  }
}

func changeScore3(score: Int) -> Int {
  return score + 2
}

var scores3 = [36, 61, 78, 89, 99]
changeScore(scores: &scores3, changeMethod: changeScore3)

print(scores3)

// changeScore函数只能适用于分数
// 优化 使用高阶函数map将数组元素映射成另一个值
let results = scores3.map { item in
  item + 2
}

print(scores3)
print(results)

// 另外两个高阶函数
// filter
func fail(score: Int) -> Bool {
  return score < 60
}

let failScore = scores3.filter(fail)
print("未及格:", failScore)

// reduce
let reduce1 = scores3.reduce(0) { first, next in
	first + next
}

print(reduce1)

// 另一种简化写法 +就是一个函数 操作符重写
scores3.reduce(0, +)

//"0"是初始参数
//"0"和item操作后作为partialResult
//item是数组每一项
let reduce2 = scores3.reduce("") { partialResult, item in
	partialResult + String(item) + " "
}

print(reduce2)
